package 富婆梦.算法题;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.第五周.作业
 * @ClassName: Algorithm
 * @Author: hemengjin
 * @Description: 算法题：给一个整数数组nums，和一个目标值target，数组中的两个数值加起来等一target，返回数组下标
 *               例：输入nums=[2,3,7,9] target=11  输出[0,3]
 * @Date:2021/8/22 10:13
 * @Version: 1.0
 */
public class Algorithm {
    public static void main(String[] args) {
        Algorithm al = new Algorithm();
        ArrayList<Integer> num = al.getNum();

        ArrayList<Integer> index = al.getIndex(num);
        if (index==null) {
            System.out.println("对不起，没找到你的符合你target的数字哦！");
        } else {
            al.printResult(index);
        }


    }

    //获得输入值的方法
    public ArrayList<Integer> getNum() {
        ArrayList<Integer> list = new ArrayList();
        System.out.println("请输入您的数组，以逗号隔开");
        Scanner sc = new Scanner(System.in);
        String string = sc.next();
        System.out.println("请输入您的target");
        int targrt = sc.nextInt();
        String[] strings = string.split(",");
        for (String s : strings) {
            list.add(Integer.valueOf(s));
        }
        list.add(targrt);
        return list;
    }

    public ArrayList<Integer> getIndex(ArrayList<Integer> list) {
        int target = list.get(list.size() - 1);
        ArrayList<Integer> index = new ArrayList<>();
        for (int i = 0; i < list.size() - 2; i++) {
            for (int j = i + 1; j < list.size() - 1; j++) {
                if ((list.get(i) + list.get(j)) == target) {
                    index.add(i);
                    index.add(j);
                    return index;
                }
            }
        }
        return null;
    }

    //输出结果
    public void printResult(ArrayList<Integer> index) {
        System.out.print("结果为：");
        System.out.print("[");
        for (int i = 0; i < index.size(); i++) {
            if (i < index.size() - 1) {
                System.out.print(index.get(i) + ",");
            } else {
                System.out.print(index.get(i));
            }

        }
        System.out.print("]");
    }

}
